<template>
  <div class="coupon-manager">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="statistics">
      <el-col :span="6" v-for="item in statisticsData" :key="item.title">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-value">{{ item.value }}</div>
          <div class="stat-title">{{ item.title }}</div>
          <div class="stat-change">
            较上月 {{ item.change > 0 ? '+' : ''}}{{ item.change }}%
            <i :class="item.change >= 0 ? 'el-icon-top' : 'el-icon-bottom'"
               :style="{ color: item.change >= 0 ? '#52c41a' : '#ff4d4f' }">
            </i>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增优惠券
      </el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索优惠券名称"
        class="search-input"
        clearable
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch"><el-icon><Search /></el-icon></el-button>
        </template>
      </el-input>
    </div>

    <!-- 优惠券列表 -->
    <el-table :data="couponList" stripe border v-loading="loading">
      <el-table-column prop="couponId" label="券ID" width="100" />
      <el-table-column prop="couponName" label="优惠券名称" min-width="150" />
      <el-table-column label="优惠券类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getCouponTypeTag(row.couponType)">
            {{ getCouponTypeText(row.couponType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优惠内容" width="150">
        <template #default="{ row }">
          <span v-if="row.couponType === 1">
            满{{ row.minOrderAmount }}减{{ row.amount }}
          </span>
          <span v-else-if="row.couponType === 2">
            {{ row.amount }}折
          </span>
          <span v-else>
            立减{{ row.amount }}元
          </span>
        </template>
      </el-table-column>
      <el-table-column label="有效期" width="240">
        <template #default="{ row }">
          {{ row.startTime }} 至 {{ row.endTime }}
        </template>
      </el-table-column>
      <el-table-column label="发放/剩余" width="120">
        <template #default="{ row }">
          {{ row.remainingCount }}/{{ row.totalCount }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-switch
            v-model="row.couponStatus"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button 
            type="success" 
            size="small" 
            @click="showIssuanceDialog(row)"
          >
            发放
          </el-button>
          <el-button 
            type="info" 
            size="small" 
            @click="showStatistics(row)"
          >
            统计
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑优惠券抽屉 -->
    <el-drawer
      v-model="showDrawer"
      :title="isEdit ? '编辑优惠券' : '新增优惠券'"
      size="600px"
      :destroy-on-close="true"
    >
      <el-form 
        :model="couponForm" 
        :rules="rules" 
        ref="couponFormRef"
        label-width="100px"
        class="coupon-form"
      >
        <el-form-item label="优惠券名称" prop="couponName">
          <el-input v-model="couponForm.couponName" placeholder="请输入优惠券名称" />
        </el-form-item>
        
        <el-form-item label="优惠券类型" prop="couponType">
          <el-select v-model="couponForm.couponType" placeholder="请选择优惠券类型">
            <el-option label="满减券" :value="1" />
            <el-option label="折扣券" :value="2" />
            <el-option label="无门槛券" :value="3" />
          </el-select>
        </el-form-item>
        
        <el-form-item 
          label="优惠金额" 
          prop="amount"
          :rules="[
            { required: true, message: '请输入优惠金额', trigger: 'blur' },
            { validator: validateAmount, trigger: 'blur' }
          ]"
        >
          <el-input-number 
            v-model="couponForm.amount" 
            :min="0"
            :precision="couponForm.couponType === 2 ? 1 : 2"
            :max="couponForm.couponType === 2 ? 9.9 : 99999"
          />
          <span class="unit">{{ couponForm.couponType === 2 ? '折' : '元' }}</span>
        </el-form-item>
        
        <el-form-item 
          v-if="couponForm.couponType === 1" 
          label="最低消费" 
          prop="minOrderAmount"
        >
          <el-input-number 
            v-model="couponForm.minOrderAmount" 
            :min="0"
            :precision="2"
          />
          <span class="unit">元</span>
        </el-form-item>
        
        <el-form-item label="有效期" prop="validPeriod">
          <el-date-picker
            v-model="couponForm.validPeriod"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        
        <el-form-item label="发放总量" prop="totalCount">
          <el-input-number 
            v-model="couponForm.totalCount" 
            :min="1"
            :precision="0"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="couponStatus">
          <el-switch
            v-model="couponForm.couponStatus"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="drawer-footer">
          <el-button @click="showDrawer = false">取消</el-button>
          <el-button type="primary" @click="saveCoupon">确定</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 发放优惠券对话框 -->
    <el-dialog
      title="发放优惠券"
      v-model="showIssuanceDialog"
      width="500px"
    >
      <el-form :model="issuanceForm" label-width="100px">
        <el-form-item label="发放方式">
          <el-radio-group v-model="issuanceForm.type">
            <el-radio :label="1">指定用户</el-radio>
            <el-radio :label="2">全部用户</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item 
          v-if="issuanceForm.type === 1" 
          label="选择用户"
        >
          <el-select
            v-model="issuanceForm.users"
            multiple
            filterable
            placeholder="请选择用户"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.username"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showIssuanceDialog = false">取消</el-button>
        <el-button type="primary" @click="handleIssue">确定发放</el-button>
      </template>
    </el-dialog>

    <!-- 优惠券统计对话框 -->
    <el-dialog
      title="优惠券使用统计"
      v-model="showStatisticsDialog"
      width="700px"
    >
      <div class="statistics-content">
        <div class="stat-row">
          <div class="stat-item">
            <div class="label">发放总量</div>
            <div class="value">{{ currentStats.totalCount }}</div>
          </div>
          <div class="stat-item">
            <div class="label">已领取</div>
            <div class="value">{{ currentStats.claimedCount }}</div>
          </div>
          <div class="stat-item">
            <div class="label">已使用</div>
            <div class="value">{{ currentStats.usedCount }}</div>
          </div>
          <div class="stat-item">
            <div class="label">使用率</div>
            <div class="value">{{ currentStats.useRate }}%</div>
          </div>
        </div>
        <div class="chart-container">
          <!-- 这里可以添加图表展示 -->
          <div class="chart-placeholder">使用趋势图表</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 统计数据
const statisticsData = ref([
  { title: '优惠券总数', value: 156, change: 12.3 },
  { title: '已使用数量', value: 86, change: 5.6 },
  { title: '领取总量', value: 235, change: -2.8 },
  { title: '剩余数量', value: 149, change: 8.9 }
])

// 搜索和分页
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 表格数据
const couponList = ref([])

// 表单数据
const showDrawer = ref(false)
const isEdit = ref(false)
const couponFormRef = ref(null)

const couponForm = reactive({
  couponId: null,
  couponName: '',
  couponType: 1,
  amount: 0,
  minOrderAmount: 0,
  validPeriod: [],
  totalCount: 1000,
  couponStatus: 1
})

// 表单验证规则
const rules = {
  couponName: [
    { required: true, message: '请输入优惠券名称', trigger: 'blur' }
  ],
  couponType: [
    { required: true, message: '请选择优惠券类型', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入优惠金额', trigger: 'blur' }
  ],
  validPeriod: [
    { required: true, message: '请选择有效期', trigger: 'change' }
  ],
  totalCount: [
    { required: true, message: '请输入发放总量', trigger: 'blur' }
  ]
}

// 优惠券类型相关
const getCouponTypeTag = (type) => {
  const typeMap = {
    1: 'success',
    2: 'warning',
    3: 'primary'
  }
  return typeMap[type]
}

const getCouponTypeText = (type) => {
  const textMap = {
    1: '满减券',
    2: '折扣券',
    3: '无门槛券'
  }
  return textMap[type]
}

// 金额验证
const validateAmount = (rule, value, callback) => {
  if (couponForm.couponType === 2 && value > 9.9) {
    callback(new Error('折扣不能大于9.9折'))
  } else {
    callback()
  }
}

// 发放相关
const showIssuanceDialog = ref(false)
const issuanceForm = reactive({
  type: 1,
  users: []
})
const userList = ref([
  { id: 1, username: '用户1' },
  { id: 2, username: '用户2' }
])

// 统计相关
const showStatisticsDialog = ref(false)
const currentStats = reactive({
  totalCount: 0,
  claimedCount: 0,
  usedCount: 0,
  useRate: 0
})

// 加载数据
const loadData = () => {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    couponList.value = Array.from({ length: 10 }).map((_, index) => ({
      couponId: index + 1,
      couponName: `优惠券${index + 1}`,
      couponType: Math.floor(Math.random() * 3) + 1,
      amount: Math.floor(Math.random() * 100) + 1,
      minOrderAmount: Math.floor(Math.random() * 200) + 100,
      startTime: '2024-01-01',
      endTime: '2024-12-31',
      totalCount: 1000,
      remainingCount: Math.floor(Math.random() * 1000),
      couponStatus: Math.random() > 0.5 ? 1 : 0
    }))
    total.value = 100
    loading.value = false
  }, 500)
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadData()
}

// 新增优惠券
const handleAdd = () => {
  isEdit.value = false
  Object.assign(couponForm, {
    couponId: null,
    couponName: '',
    couponType: 1,
    amount: 0,
    minOrderAmount: 0,
    validPeriod: [],
    totalCount: 1000,
    couponStatus: 1
  })
  showDrawer.value = true
}

// 保存优惠券
const saveCoupon = async () => {
  if (!couponFormRef.value) return
  
  try {
    await couponFormRef.value.validate()
    // 模拟保存请求
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
    showDrawer.value = false
    loadData()
  } catch (error) {
    console.log('表单验证失败', error)
  }
}

// 编辑优惠券
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(couponForm, {
    ...row,
    validPeriod: [new Date(row.startTime), new Date(row.endTime)]
  })
  showDrawer.value = true
}

// 修改优惠券状态
const handleStatusChange = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.couponStatus ? '启用' : '禁用'}该优惠券吗？`,
      '提示'
    )
    ElMessage.success(`${row.couponStatus ? '启用' : '禁用'}成功`)
  } catch {
    row.couponStatus = !row.couponStatus
  }
}

// 显示优惠券统计
const showStatistics = (row) => {
  Object.assign(currentStats, {
    totalCount: row.totalCount,
    claimedCount: row.totalCount - row.remainingCount,
    usedCount: Math.floor(Math.random() * (row.totalCount - row.remainingCount)),
    useRate: Math.floor(Math.random() * 100)
  })
  showStatisticsDialog.value = true
}

// 发放优惠券
const handleIssue = async () => {
  if (issuanceForm.type === 1 && !issuanceForm.users.length) {
    ElMessage.warning('请选择发放用户')
    return
  }
  
  try {
    await ElMessageBox.confirm('确定要发放优惠券吗？', '提示')
    // 模拟发放请求
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success('发放成功')
    showIssuanceDialog.value = false
    loadData()
  } catch {
    // 取消发放
  }
}

// 初始化
loadData()
</script>

<style lang="scss" scoped>
.coupon-manager {
  padding: 20px;
  
  .statistics {
    margin-bottom: 20px;
  }
  
  .action-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    padding: 18px 24px 18px 24px;
    margin-bottom: 20px;
    gap: 20px;

    .el-button {
      min-width: 120px;
    }
    .search-input {
      max-width: 320px;
      flex: 1;
      margin-left: 20px;
    }
  }
  
  .el-table {
    margin-bottom: 20px;
  }
  
  .pagination {
    text-align: right;
  }
  
  .drawer-footer {
    text-align: right;
  }
  
  .statistics-content {
    padding: 20px;
    
    .stat-row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      
      .stat-item {
        flex: 1;
        text-align: center;
        
        .label {
          font-size: 14px;
          color: #999;
        }
        
        .value {
          font-size: 18px;
          font-weight: bold;
        }
      }
    }
    
    .chart-container {
      height: 200px;
      background-color: #f5f5f5;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #999;
    }
  }
}
</style>
